const Router = require('koa-router');
const plyfeaCtl= require('../../controllers/playerfeatures.js')
const cmptCtl= require('../../controllers/competitions.js')
const playerCtl= require('../../controllers/players.js')
const teamCtl= require('../../controllers/teams.js');
const { ResumeToken } = require('mongodb');
const router = new Router();

/**
 * @swagger
 * tags:
 *   - name: competition
 *     description: Everything about competition
 */

router
/**
 * @swagger
 * paths:
 *   /competitions:
 *     get:
 *       tags:
 *         - competition
 *       summary: Return a list of competitions
 *       description: ''
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 *           schema:
 *             type: array
 *             items:
 *               $ref: '#/definitions/Competition'
 */
    .get('/', async (ctx, next)=>{ ctx.body = await plyfeaCtl.list(); })

/**
 * @swagger
 * paths:
 *   /competitions:
 *     post:
 *       tags:
 *         - competition
 *       summary: Create a competition
 *       description: ''
 *       parameters:
 *         - in: body
 *           name: "body"
 *           description: ""
 *           required: true
 *           schema:
 *             $ref: "#/definitions/Competition"
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .post('/', async (ctx, next)=>{
        const {id} = ctx.params;
        const data = ctx.request.body;
        let  r = await plyfeaCtl.create(data);
        ctx.body = r;
    })
/**
 * @swagger
 * paths:
 *   /competitions/{cid}:
 *     get:
 *       tags:
 *         - competition
 *       summary: Return a competition
 *       description: ''
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 *           schema:
 *             $ref: '#/definitions/Competition'
 */
    .get('/:id', async (ctx, next)=>{
        // Retrieves informations about a given competition
        const {id} = ctx.params;
        const r = await plyfeaCtl.retrieve(id);
        ctx.assert(r !== null, 404, 'Detail not found!');

        ctx.body = r;
    })

/**
 * @swagger
 * paths:
 *   /competitions/{cid}:
 *     put:
 *       tags:
 *         - competition
 *       summary: Update or create a competition
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *         - in: body
 *           name: body
 *           description: ""
 *           required: true
 *           schema:
 *             $ref: "#/definitions/Competition"
 *
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .put('/:id', async (ctx, next)=>{
        const id = ctx.params.id;
        const data = ctx.request.body;
        const r = await plyfeaCtl.upsert(id, data);
        
        ctx.body = r;
    })

/**
 * @swagger
 * paths:
 *   /competitions/{cid}:
 *     delete:
 *       tags:
 *         - competition
 *       summary: Delete a competition
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *
 *       produces:
 *         - application/json
 *       responses:
 *         204:
 *           description: No content
 */
    .delete('/:id', async (ctx, next)=>{
        plyfeaCtl.removeById(ctx.params.id);
        ctx.status = 204;
    })
/**
 * @swagger
 * paths:
 *   /competitions/{cid}/seasons:
 *     get:
 *       tags:
 *         - competition
 *       summary: Return the list of seasons of the given competition
 *       description: ""
 *       parameters:
 *         - in: path
 *           name: cid 
 *           description: ""
 *           required: true
 *           type: string
 *
 *       produces:
 *         - application/json
 *       responses:
 *         200:
 *           description: OK
 */
    .get('/:id/seasons', async (ctx, next)=>{
        const {id} = ctx.params;
        ctx.body = "TODO find the list of seasons of competition" + id;
        ctx.throw(500);
    })

    .get('/:seasonid/:playerid', async (ctx, next)=>{
        const {seasonid, playerid} = ctx.params;
        const player = await plyfeaCtl.find({playerId: playerid});
        let result = [], goals = 0, assists = 0, appearance = 0, minutes = 0, yellowCard = 0, redCard = 0, attackScore = 0, defenseScore = 0, organizeScore = 0,
        skillScore = 0, setScore = 0, passScore = 0, i = 0;
        for (let a of player){
            for (let key of Object.keys(a)){
                let b = a[key]
                for (let key1 of Object.keys(b)){
                    let playeridt = b[key1]
                    if (key1 == seasonid){
                        goals = goals + playeridt.totalGoal;
                        assists = assists + playeridt.totalAssist;
                        appearance = appearance + playeridt.appearance;
                        minutes = minutes + playeridt.minutes;
                        attackScore = attackScore + playeridt.attackScore;
                        defenseScore = defenseScore + playeridt.defenseScore;
                        organizeScore = organizeScore + playeridt.organizeScore;
                        skillScore = skillScore + playeridt.skillScore;
                        setScore = setScore + playeridt.setScore;
                        passScore = passScore + playeridt.passScore;
                        yellowCard = yellowCard + playeridt.yellowCard;
                        redCard = redCard + playeridt.redCard;
                        i++
                    }
                    else {
                        continue;
                    }
                }
            }
        }
        let obj = {};
        obj.playerId = parseInt(playerid);
        obj.goals = goals;
        obj.assists = assists;
        obj.appearance = appearance;
        obj.minutes = minutes;
        obj.attackScore = parseFloat((attackScore / i).toFixed(2));
        obj.defenseScore = parseFloat((defenseScore / i).toFixed(2));
        obj.organizeScore = parseFloat((organizeScore / i).toFixed(2));
        obj.skillScore = parseFloat((skillScore / i).toFixed(2));
        obj.setScore = parseFloat((setScore / i).toFixed(2));
        obj.passScore = parseFloat((passScore / i).toFixed(2));
        obj.yellowCard = yellowCard;
        obj.redCard = redCard;
        result.push(obj);
        ctx.body = result;
    })

    .get('/league/list/:playerid', async (ctx, next)=>{
        const {playerid} = ctx.params;
        const player = await plyfeaCtl.find({playerId: playerid});
        let result = [];
        for (let a of player){
            for (let key1 of Object.keys(a)){
                if (parseFloat(key1).toString() != "NaN"){
                    for (let key2 of Object.keys(a[key1])){
                        let obj = {};
                        let playersea = a[key1][key2];
                        obj.season = key2;
                        const cmpt = await cmptCtl.find({competitionId: key1});
                        for (let b of cmpt){
                            obj.leagueLogo = b.competitionLogo;
                            obj.league = b.competitionShortName;
                        }
                        obj.teamId = playersea['teamId'];
                        const t = await teamCtl.find({teamId: playersea['teamId']})
                        for (let c of t){
                            for (let key3 of Object.keys(c['name'])){
                                if (key3 == key2){
                                    let teams = c['name'][key3];
                                    obj.teamLogo = teams.teamImg;
                                    obj.team = teams.offcialName.slice(0,4);
                                }
                                else {
                                    continue;
                                }
                            }
                        }
                        obj.minutes = playersea.minutes;
                        obj.appearance = playersea.appearance + '/' + playersea.lineUp;
                        obj.cards = playersea.yellowCard + '/' + playersea.redCard;
                        const playerInfor = await playerCtl.find({playerId: playerid});
                        for (let d of playerInfor){
                            switch (d.role) {
                                case 'GK':
                                    obj.role = '门将';
                                    break;
                                case 'DF':
                                    obj.role = '后卫';
                                    break;
                                case 'MF':
                                    obj.role = '中场';
                                    break;
                                case 'ST':
                                    obj.role = '前锋';
                                    break;
                                default:
                                    break;
                            }
                            for (let key4 of Object.keys(d['team'])){
                                if (key4 == key2){
                                    let team = d['team'][key4];
                                    obj.jerseyNumber = team.teamNum;
                                }
                                else {
                                    continue;
                                }
                            }
                        }
                        result.push(obj);
                    }
                }
                else {
                    continue;
                }
            }
        }
        ctx.body = result;
    })

    .get('/shot/:competitionid/:seasonid/:playerid', async (ctx, next)=>{
        const {competitionid, seasonid, playerid} = ctx.params;
        const features = await plyfeaCtl.list();
        let shot = [], goal = [];
        for (let a of features){
            for (let key of Object.keys(a)){
                if (key == competitionid){
                    for (let key1 of Object.keys(a[key])){
                        if (key1 == seasonid){
                            let playerfea = a[key][key1];
                            let obj = {
                                'rank': 0,
                                'playerId': a.playerId,
                                'name': 0,
                                'total': playerfea.totalGoal,
                                'average': (playerfea.totalGoal / playerfea.minutes || 0) * 90,
                                'xG': playerfea.xG
                            }
                            let obj1 = {
                                'rank': 0,
                                'playerId': a.playerId,
                                'name': 0,
                                'total': playerfea.totalShot,
                                'average': (playerfea.totalShot / playerfea.minutes || 0) * 90,
                                'xG_Shot': (playerfea.xG / playerfea.totalShot || 0)
                            }
                            shot.push(obj1);
                            goal.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
        }
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        shot = shot.sort(compare('total'));
        goal = goal.sort(compare('total'));
        let i1 = 0, i2 = 0;
        for (let a of goal){
            i1++;
            a.rank = i1;
            a.average = parseFloat(a['average'].toFixed(2));
            a.xG = parseFloat(a['xG'].toFixed(2));
        }
        for (let b of shot){
            i2++;
            b.rank = i2;
            b.average = parseFloat(b['average'].toFixed(2));
            b['xG_Shot'] = parseFloat(b['xG_Shot'].toFixed(2));
        }
        //console.log(shot);
        let goalData = [], shotData = [], result = {};
        for (let a of goal){
            if (a.playerId == playerid) {
                if (a.rank <= 5){
                    for(let b of goal) {
                        if(b.rank <=8) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            goalData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of goal){
                        if(b.rank == 1) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            goalData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            goalData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        for (let a of shot){
            if (a.playerId == playerid) {
                if (a.rank <= 5){
                    for(let b of shot) {
                        if(b.rank <=8) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            shotData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of shot){
                        if(b.rank == 1) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            shotData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            shotData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        result.goalData = goalData;
        result.shotData = shotData;
        ctx.body = result;
    })

    .get('/assist/:competitionid/:seasonid/:playerid', async (ctx, next)=>{
        const {competitionid, seasonid, playerid} = ctx.params;
        const features = await plyfeaCtl.list();
        let shotassist = [], assist = [];
        for (let a of features){
            for (let key of Object.keys(a)){
                if (key == competitionid){
                    for (let key1 of Object.keys(a[key])){
                        if (key1 == seasonid){
                            let playerfea = a[key][key1];
                            let obj = {
                                'rank': 0,
                                'playerId': a.playerId,
                                'name': 0,
                                'total': playerfea.totalAssist,
                                'average': (playerfea.totalAssist / playerfea.minutes || 0) * 90,
                                'xA': playerfea.xA
                            }
                            let obj1 = {
                                'rank': 0,
                                'playerId': a.playerId,
                                'name': 0,
                                'total': playerfea.totalShotAssist,
                                'average': (playerfea.totalShotAssist / playerfea.minutes || 0) * 90,
                                //'xG/Shot': (playerfea.xG / playerfea.totalShot || 0)
                            }
                            shotassist.push(obj1);
                            assist.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
        }
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        assist = assist.sort(compare('total'));
        shotassist = shotassist.sort(compare('total'));
        let i1 = 0, i2 = 0;
        for (let a of assist){
            i1++;
            a.rank = i1;
            a.average = parseFloat(a['average'].toFixed(2));
            a.xA = parseFloat(a['xA'].toFixed(2));
        }
        for (let b of shotassist){
            i2++;
            b.rank = i2;
            b.average = parseFloat(b['average'].toFixed(2));
            //b['xG/Shot'] = parseFloat(b['xG/Shot'].toFixed(2));
        }
        //console.log(shot);
        let assistData = [], shotassistData = [], result = {};
        for (let a of assist){
            if (a.playerId == playerid) {
                if (a.rank <= 5){
                    for(let b of assist) {
                        if(b.rank <=8) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            assistData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of assist){
                        if(b.rank == 1) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            assistData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            assistData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        for (let a of shotassist){
            if (a.playerId == playerid) {
                if (a.rank <= 5){
                    for(let b of shotassist) {
                        if(b.rank <=8) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            shotassistData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of shotassist){
                        if(b.rank == 1) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            shotassistData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            shotassistData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        result.assistData = assistData;
        result.shotAssistData = shotassistData;
        ctx.body = result;
    })

    .get('/pass/:competitionid/:seasonid/:playerid', async (ctx, next)=>{
        const {competitionid, seasonid, playerid} = ctx.params;
        const features = await plyfeaCtl.list();
        let pass = [], cross = [];
        for (let a of features){
            for (let key of Object.keys(a)){
                if (key == competitionid){
                    for (let key1 of Object.keys(a[key])){
                        if (key1 == seasonid){
                            let playerfea = a[key][key1];
                            let obj = {
                                'rank': 0,
                                'playerId': a.playerId,
                                'name': 0,
                                'total': playerfea.totalPass,
                                'average': (playerfea.totalPass / playerfea.minutes || 0) * 90,
                                'rate': playerfea['passAccuracy']
                            }
                            let obj1 = {
                                'rank': 0,
                                'playerId': a.playerId,
                                'name': 0,
                                'total': playerfea.totalCross,
                                'average': (playerfea.totalCross / playerfea.minutes || 0) * 90,
                                'rate': playerfea['crossAccuracy']
                                //'xG/Shot': (playerfea.xG / playerfea.totalShot || 0)
                            }
                            cross.push(obj1);
                            pass.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
        }
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        cross = cross.sort(compare('total'));
        pass = pass.sort(compare('total'));
        let i1 = 0, i2 = 0;
        for (let a of pass){
            i1++;
            a.rank = i1;
            a.average = parseFloat(a['average'].toFixed(2));
            //a.rate = parseFloat(a['rate'].toFixed(2));
            a.rate = parseFloat(parseFloat(a['rate']).toFixed(2));
        }
        for (let b of cross){
            i2++;
            b.rank = i2;
            b.average = parseFloat(b['average'].toFixed(2));
            b.rate = parseFloat(parseFloat(b['rate']).toFixed(2));
        }
        //console.log(shot);
        let passData = [], crossData = [], result = {};
        for (let a of pass){
            if (a.playerId == playerid) {
                if (a.rank <= 5){
                    for(let b of pass) {
                        if(b.rank <=8) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            passData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of pass){
                        if(b.rank == 1) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            passData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            passData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        for (let a of cross){
            if (a.playerId == playerid) {
                if (a.rank <= 5){
                    for(let b of cross) {
                        if(b.rank <=8) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            crossData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of cross){
                        if(b.rank == 1) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            crossData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            crossData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        result.passData = passData;
        result.crossData = crossData;
        ctx.body = result;
    })

    .get('/touch/:competitionid/:seasonid/:playerid', async (ctx, next)=>{
        const {competitionid, seasonid, playerid} = ctx.params;
        const features = await plyfeaCtl.list();
        let touch = [], duel = [];
        for (let a of features){
            for (let key of Object.keys(a)){
                if (key == competitionid){
                    for (let key1 of Object.keys(a[key])){
                        if (key1 == seasonid){
                            let playerfea = a[key][key1];
                            let obj = {
                                'rank': 0,
                                'playerId': a.playerId,
                                'name': 0,
                                'total': playerfea.totalTouch,
                                'average': (playerfea.totalTouch / playerfea.minutes || 0) * 90,
                                'touchinbox': playerfea.touchInBox
                            }
                            let obj1 = {
                                'rank': 0,
                                'playerId': a.playerId,
                                'name': 0,
                                'total': playerfea.totalDuel,
                                'average': (playerfea.totalDuel / playerfea.minutes || 0) * 90,
                                'rate': (playerfea.duelSuccess / playerfea.totalDuel || 0)
                                //'xG/Shot': (playerfea.xG / playerfea.totalShot || 0)
                            }
                            duel.push(obj1);
                            touch.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
        }
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        touch = touch.sort(compare('total'));
        duel = duel.sort(compare('total'));
        let i1 = 0, i2 = 0;
        for (let a of touch){
            i1++;
            a.rank = i1;
            a.average = parseFloat(a['average'].toFixed(2));
            //a.xA = parseFloat(a['xA'].toFixed(2));
        }
        for (let b of duel){
            i2++;
            b.rank = i2;
            b.average = parseFloat(b['average'].toFixed(2));
            b.rate = parseFloat(b['rate'].toFixed(2))
            //b['xG/Shot'] = parseFloat(b['xG/Shot'].toFixed(2));
        }
        //console.log(shot);
        let touchData = [], duelData = [], result = {};
        for (let a of touch){
            if (a.playerId == playerid) {
                if (a.rank <= 5){
                    for(let b of touch) {
                        if(b.rank <=8) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            touchData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of touch){
                        if(b.rank == 1) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            touchData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            touchData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        for (let a of duel){
            if (a.playerId == playerid) {
                if (a.rank <= 5){
                    for(let b of duel) {
                        if(b.rank <=8) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            duelData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of duel){
                        if(b.rank == 1) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            duelData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            duelData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        result.touchData = touchData;
        result.duelData = duelData;
        ctx.body = result;
    })

    .get('/dribble/:competitionid/:seasonid/:playerid', async (ctx, next)=>{
        const {competitionid, seasonid, playerid} = ctx.params;
        const features = await plyfeaCtl.list();
        let dribble = [], takeon = [];
        for (let a of features){
            for (let key of Object.keys(a)){
                if (key == competitionid){
                    for (let key1 of Object.keys(a[key])){
                        if (key1 == seasonid){
                            let playerfea = a[key][key1];
                            let obj = {
                                'rank': 0,
                                'playerId': a.playerId,
                                'name': 0,
                                'total': playerfea.totalDribble,
                                'average': (playerfea.totalDribble / playerfea.minutes || 0) * 90,
                                'dribbleAvgDistance': playerfea.dribbleAvgDistance
                            }
                            let obj1 = {
                                'rank': 0,
                                'playerId': a.playerId,
                                'name': 0,
                                'total': playerfea.totalTakeOn,
                                'average': (playerfea.totalTakeOn / playerfea.minutes || 0) * 90,
                                'rate': (playerfea.takeOnSuccess / playerfea.totalTakeOn || 0)
                                //'xG/Shot': (playerfea.xG / playerfea.totalShot || 0)
                            }
                            takeon.push(obj1);
                            dribble.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
        }
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        dribble = dribble.sort(compare('total'));
        takeon = takeon.sort(compare('total'));
        let i1 = 0, i2 = 0;
        for (let a of dribble){
            i1++;
            a.rank = i1;
            a.average = parseFloat(a['average'].toFixed(2));
            a.dribbleAvgDistance = parseFloat(a['dribbleAvgDistance'].toFixed(2))
            //a.xA = parseFloat(a['xA'].toFixed(2));
        }
        for (let b of takeon){
            i2++;
            b.rank = i2;
            b.average = parseFloat(b['average'].toFixed(2));
            b.rate = parseFloat(b['rate'].toFixed(2))
            //b['xG/Shot'] = parseFloat(b['xG/Shot'].toFixed(2));
        }
        //console.log(shot);
        let dribbleData = [], takeonData = [], result = {};
        for (let a of dribble){
            if (a.playerId == playerid) {
                if (a.rank <= 5){
                    for(let b of dribble) {
                        if(b.rank <=8) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            dribbleData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of dribble){
                        if(b.rank == 1) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            dribbleData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            dribbleData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        for (let a of takeon){
            if (a.playerId == playerid) {
                if (a.rank <= 5){
                    for(let b of takeon) {
                        if(b.rank <=8) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            takeonData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of takeon){
                        if(b.rank == 1) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            takeonData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            takeonData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        result.dribbleData = dribbleData;
        result.takeonData = takeonData;
        ctx.body = result;
    })

    .get('/foul/:competitionid/:seasonid/:playerid', async (ctx, next)=>{
        const {competitionid, seasonid, playerid} = ctx.params;
        const features = await plyfeaCtl.list();
        let foul = [], fouled = [];
        for (let a of features){
            for (let key of Object.keys(a)){
                if (key == competitionid){
                    for (let key1 of Object.keys(a[key])){
                        if (key1 == seasonid){
                            let playerfea = a[key][key1];
                            let obj = {
                                'rank': 0,
                                'playerId': a.playerId,
                                'name': 0,
                                'offensiveFoul': playerfea.totalOffensiveFoul,
                                'defensiveFoul': playerfea.totalDefensiveFoul,
                                'card': playerfea.redCard + '/' + playerfea.yellowCard
                            }
                            let obj1 = {
                                'rank': 0,
                                'playerId': a.playerId,
                                'name': 0,
                                'total': playerfea.foulConceded,
                                'average': (playerfea.foulConceded / playerfea.minutes || 0) * 90,
                                //'rate': (playerfea.takeOnSuccess / playerfea.totalTakeOn || 0)
                                //'xG/Shot': (playerfea.xG / playerfea.totalShot || 0)
                            }
                            fouled.push(obj1);
                            foul.push(obj);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
        }
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        foul = foul.sort(compare('offensiveFoul'));
        fouled = fouled.sort(compare('total'));
        let i1 = 0, i2 = 0;
        for (let a of foul){
            i1++;
            a.rank = i1;
            //a.xA = parseFloat(a['xA'].toFixed(2));
        }
        for (let b of fouled){
            i2++;
            b.rank = i2;
            b.average = parseFloat(b['average'].toFixed(2));
            //b.rate = parseFloat(b['rate'].toFixed(2))
            //b['xG/Shot'] = parseFloat(b['xG/Shot'].toFixed(2));
        }
        //console.log(shot);
        let foulData = [], fouledData = [], result = {};
        for (let a of foul){
            if (a.playerId == playerid) {
                if (a.rank <= 5){
                    for(let b of foul) {
                        if(b.rank <=8) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            foulData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of foul){
                        if(b.rank == 1) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            foulData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            foulData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        for (let a of fouled){
            if (a.playerId == playerid) {
                if (a.rank <= 5){
                    for(let b of fouled) {
                        if(b.rank <=8) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            fouledData.push(b);
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    for(let b of fouled){
                        if(b.rank == 1) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            fouledData.push(b);
                        }
                        else if (b.rank >= a.rank - 3 && b.rank <= a.rank + 3) {
                            const player = await playerCtl.find({playerId: b.playerId});
                            for (let c of player){
                                b.name = c.playerName;
                                b.playerImg = c.playerImg;
                            }
                            fouledData.push(b);
                        }
                        else {continue;}
                    }
                }
            }
            else {
                continue;
            }
        }
        result.foulData = foulData;
        result.fouledData = fouledData;
        ctx.body = result;
    })

    .get('/statistic/:seasonid/:type', async (ctx, next)=>{
        const {seasonid, type} = ctx.params;
        const features = await plyfeaCtl.list();
        let result = [], preresult = [];
        function isEmptyObject(obj) {
            for (let x in obj) {
                return false;
            }
            return true;
        }
        for (let a of features) {
            let obj = {}, i = 0, yellow = 0, red = 0;
            for (let key of Object.keys(a)) {
                if (parseFloat(key).toString() != "NaN"){
                    for (let key1 of Object.keys(a[key])) {
                        if (key1 == seasonid) {
                            let plyfea = a[key][key1]
                            i++;
                            if (type == 'Offense' && plyfea.appearance >= 15) {
                                obj.rank = 0;
                                obj.playerId = a.playerId;
                                //console.log(a.playerId);
                                obj.playerImg = 0;
                                obj.playerName = 0;
                                obj.goals = parseFloat((((obj.goals || 0) + plyfea.totalGoal)).toFixed(2));
                                //obj.xg = parseFloat((((obj.xg || 0) + plyfea.xG) / i).toFixed(2));
                                //obj.appearance = plyfea.appearance
                                obj.xg = parseFloat((((obj.xg || 0) + plyfea.xG)).toFixed(2));
                                obj.target = parseFloat((((obj.target || 0) + plyfea['shots on target'])).toFixed(2));
                                obj.notTarget = parseFloat((((obj.notTarget || 0) + plyfea['shots off target'])).toFixed(2));
                                obj.saved = parseFloat((((obj.saved || 0) + plyfea['shots saved'])).toFixed(2));
                                obj.onPost = parseFloat((((obj.onPost || 0) + plyfea['shots on post'])).toFixed(2));
                                obj.blocked = parseFloat((((obj.blocked || 0) + plyfea['shots blocked'])).toFixed(2));
                                obj.rating = parseFloat((((obj.rating || 0) + plyfea['attackScore']) / i).toFixed(2));
                            }
                            else if (type == 'Defense' && plyfea.appearance >= 15) {
                                obj.rank = 0;
                                obj.playerId = a.playerId;
                                //console.log(a.playerId);
                                obj.playerImg = 0;
                                obj.playerName = 0;
                                obj.clearance = parseFloat((((obj.clearance || 0) + plyfea.clearances)).toFixed(2));
                                obj.interception = parseFloat((((obj.interception || 0) + plyfea.interceptions)).toFixed(2));
                                obj.tackle = parseFloat((((obj.tackle || 0) + plyfea.tackles)).toFixed(2));
                                obj.blockPass = parseFloat((((obj.blockPass || 0) + plyfea['blocked passes'])).toFixed(2));
                                obj.blockShot = parseFloat((((obj.blockShot || 0) + plyfea['blocked shots'])).toFixed(2));
                                obj.defenseFoul = parseFloat((((obj.defenseFoul || 0) + plyfea['totalDefensiveFoul'])).toFixed(2));
                                yellow = yellow + plyfea['yellowCard'];
                                red = red + plyfea['redCard'];
                                obj.card = yellow + '/' + red;
                                //obj.red = parseFloat((((obj.red || 0) + plyfea['redCard']) / i).toFixed(2));
                                //obj.yellow = parseFloat((((obj.yellow || 0) + plyfea['yellowCard']) / i).toFixed(2));
                                obj.airDuel = parseFloat((((obj.airDuel || 0) + plyfea['air duels'])).toFixed(2));
                                obj.rating = parseFloat((((obj.rating || 0) + plyfea['defenseScore']) / i).toFixed(2));
                            }
                            else if (type == 'SetPieces' && plyfea.appearance >= 15) {
                                obj.rank = 0;
                                obj.playerId = a.playerId;
                                //console.log(a.playerId);
                                obj.playerImg = 0;
                                obj.playerName = 0;
                                obj.xgAssist = parseFloat((((obj.xgAssist || 0) + plyfea['xA'])).toFixed(2));
                                obj.goals = parseFloat((((obj.goals || 0) + plyfea['freekick goals'])).toFixed(2));
                                obj.onTarget = parseFloat((((obj.onTarget || 0) + plyfea['freekick shots on target'])).toFixed(2));
                                obj.penalty = parseFloat((((obj.penalty || 0) + plyfea['penalty'])).toFixed(2));
                                obj.missPenalty = parseFloat((((obj.missPenalty || 0) + plyfea['penalty fail'])).toFixed(2));
                                obj.rating = parseFloat((((obj.rating || 0) + plyfea['setScore']) / i).toFixed(2));
                            }
                            else if (type == 'Organization' && plyfea.appearance >= 15) {
                                obj.rank = 0;
                                obj.playerId = a.playerId;
                                //console.log(a.playerId);
                                obj.playerImg = 0;
                                obj.playerName = 0;
                                obj.assist = parseFloat((((obj.assist || 0) + plyfea['totalAssist'])).toFixed(2));
                                obj.createChance = parseFloat((((obj.createChance || 0) + plyfea['chances_created'])).toFixed(2));
                                obj.accuratePass = parseFloat((((obj.accuratePass || 0) + plyfea['passes success'])).toFixed(2));
                                obj.passAccuracy = parseFloat((((obj.passAccuracy || 0) + plyfea['passAccuracy']) / i).toFixed(2));
                                obj.rating = parseFloat((((obj.rating || 0) + plyfea['organizeScore']) / i).toFixed(2));
                            }
                            else if (type == 'Skill' && plyfea.appearance >= 15) {
                                obj.rank = 0;
                                obj.playerId = a.playerId;
                                //console.log(a.playerId);
                                obj.playerImg = 0;
                                obj.playerName = 0;
                                obj.foulConceded = parseFloat((((obj.foulConceded || 0) + plyfea['foulConceded'])).toFixed(2));
                                obj.dribble = parseFloat((((obj.dribble || 0) + plyfea['totalDribble'])).toFixed(2));
                                obj.takeOn = parseFloat((((obj.takeOn || 0) + plyfea['totalTakeOn'])).toFixed(2));
                                obj.dispossessed = parseFloat((((obj.dispossessed || 0) + plyfea['dispossessed'])).toFixed(2));
                                obj.rating = parseFloat((((obj.rating || 0) + plyfea['skillScore']) / i).toFixed(2));
                            }
                            else if (type == 'Keeper' && plyfea.appearance >= 15) {
                                obj.rank = 0;
                                obj.playerId = a.playerId;
                                //console.log(a.playerId);
                                obj.playerImg = 0;
                                obj.playerName = 0;
                                obj.save = parseFloat((((obj.rating || 0) + plyfea['totalSave'])).toFixed(2));
                                obj.savePenalty = parseFloat((((obj.rating || 0) + plyfea['keeper penalty faced success'])).toFixed(2));
                                obj.smother = parseFloat((((obj.rating || 0) + plyfea['totalSmother'])).toFixed(2));
                                obj.cleanSheet = parseFloat((((obj.rating || 0) + plyfea['clean_sheet'])).toFixed(2));
                                obj.rating = parseFloat((((obj.rating || 0) + plyfea['keeperScore']) / i).toFixed(2));
                            }
                        }
                        else {
                            continue;
                        }
                    }
                }
                else {
                    continue;
                }
            }
            //console.log(isEmptyObject(obj))
            if (isEmptyObject(obj) != true) {
                preresult.push(obj);
            }
            else {
                continue;
            }
        }
        function compare(property){
            return function(a,b){
                var value1 = a[property];
                var value2 = b[property];
                return value2 - value1;
            }
        }
        preresult = preresult.sort(compare('rating'));
        //console.log(preresult)
        let h = 0;
        for (let a of preresult) {
            h++;
            if (h <= 15) {
                a.rank = h;
                const player = await playerCtl.find({playerId: a.playerId});
                for (let b of player) {
                    a.playerImg = b.playerImg;
                    a.playerName = b.playerName;
                }
                result.push(a);
            }
            else {
                break;
            }
        }
        ctx.body = result;
    })

module.exports = router;

/**
 * @swagger
 * resourcePath: /api
 * description: All about API
 * definitions:
 *   Competition:
 *     type: "object"
 *     required:
 *       - "name"
 *     properties:
 *       id:
 *         type: "string"
 *       name:
 *         type: "string"
 *       area:
 *         type: "string"
 *       foramt:
 *         type: "string"
 *         enum:
 *           - "Domestic cup"
 *           - "Domestic league"
 *           - "Domestic super cup"
 *           - "International cup"
 *           - "International super cup"
 *       type:
 *         type: "string"
 *         enum:
 *          - club
 *          - inernational
 *       categroy: 
 *         type: "string"
 *         enum:
 *          - defalut
 *          - U12
 *          - U13
 *          - U14
 *          - U15
 *          - U16
 *          - U17
 *          - U18
 *          - U19
 *          - U20
 *          - U21
 *          - U22
 *          - U23
 *       gender: 
 *         type: "string"
 *         enum:
 *           - male
 *           - female
 *       divisionLevel:
 *         type: "number"
 *         enum:
 *           - 0
 *           - 1
 *           - 2
 *           - 3
 *           - 4
 *           - 5
 */